package com.dbtools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 * This class generates SQL DDL scripts for a given target database using Hibernate.
 */
public class Generate
{
	public static void main(String args[])
	{
		String dbModelFilePath = args[0]; // repository dbmodels xml files to process
		String dbType = args[1]; // The type of the database
		String dbModelPath = args[2]; // directory of dbmodels xml files
		String outputFile = args[3]; // output file for the Hibernate generation process
		try
		{
			File files = new File(dbModelFilePath);
			File dbModelDir = new File(dbModelPath);

			if (!new File(outputFile).getParentFile().canWrite())
			{
				throw new Exception("Output file is not writable");
			}

			BufferedReader reader = new BufferedReader(new FileReader(files));

			Configuration cfg = new Configuration();

			while (reader.ready())
			{
				String fileName = reader.readLine().trim();
				File dbModelFile = new File(dbModelDir, fileName);

				if (dbModelFile.getName().endsWith("hbm.xml"))
				{
					System.out.println("Adding DB model file " + dbModelFile);
					cfg.addFile(dbModelFile);
				}
				else
				{
					System.out.println("Ignoring DB model file " + dbModelFile);
				}
			}

			cfg.setProperty("hibernate.dialect", dbType);
			cfg.setProperty("delimiter", ";");

			SchemaExport se = new SchemaExport(cfg);

			se.setDelimiter(";");
			se.setFormat(true);
			se.setOutputFile(outputFile);

			// launch Hibernate generation
			se.create(true, false);

			// dispose all the resources after using them.
			reader.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
